<?php
/**
 * Created by PhpStorm.
 * User: mayn
 * Date: 2018/8/31
 * Time: 11:46
 */

namespace app\api\controller\v1;

use app\api\model\Article as ArticleModel;
use app\api\validate\ArticleNew;
use app\api\validate\BaseValidate;
use app\api\validate\IDMustBePositiveInt;
use app\lib\exception\ArticleException;
use app\lib\exception\SuccessMessage;
use think\Validate;

class Article
{
    public function get($id) {
        (new IDMustBePositiveInt())->goCheck();
        $article = ArticleModel::getArticleById($id);
        if (!$article) {
            throw new ArticleException([
                'msg' => 'The required article is not found'
            ]);
        }
        return $article;
    }
    public function update() {
        $validate = new BaseValidate([
            'id' => 'require|isPositiveInteger',
            'title' => 'require|min:1|max:50',
            'content' => 'require|isNotEmpty'
        ]);
        $validate->goCheck();

        $params = input('put.');
        $params = $validate->getDataByRule($params);

        // 根据文章id查询数据库，判断是否存在文章
        $article = ArticleModel::get($params['id']);
        if (!$article) {
            throw new ArticleException();
        }

        $result = ArticleModel::update($params);
        return new SuccessMessage();
    }
    public function create() {
        $validate = new ArticleNew();
        $validate->goCheck();

        $params = input('post.');
        $params = $validate->getDataByRule($params);
        $result = ArticleModel::create($params);
        return new SuccessMessage();
    }
    public function delete($id) {
        (new IDMustBePositiveInt())->goCheck();
        $article = ArticleModel::get($id);
        if (!$article) {
            throw new ArticleException();
        }
        ArticleModel::destroy([$id]);
        return new SuccessMessage();
    }
}